package top.infopub.mgr.bpa.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.infopub.dto.bpa.BpaPublicProInfoDto;
import top.infopub.dto.bpa.BudgetBatchDetailDto;
import top.infopub.dto.bpa.BudgetListDto;
import top.infopub.dto.bpa.BudgetListVo;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.bpa.dao.BpaContractBpaReviewDao;
import top.infopub.mgr.bpa.dao.BudgetBatchDao;
import top.infopub.mgr.bpa.dao.BudgetBatchInfoDao;
import top.infopub.mgr.bpa.dao.BudgetContractDao;
import top.infopub.mgr.bpa.domain.BudgetBatchDomain;
import top.infopub.mgr.bpa.jsonVo.BudgetBatchDetailJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.BudgetBatchService;
import top.infopub.mgr.bpa.vo.BudgetBatchVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.ProjectInfoService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.util.FileAttrUtils;
import top.infopub.model.bpa.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.util.*;

@Service
public class BudgetBatchServiceImpl extends GenericServiceImpl<BudgetBatch, String> implements
		BudgetBatchService {
	@Autowired
    private SetupProService setupProService;
	
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private BudgetBatchDao budgetBatchDao;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private BpaContractBpaReviewDao bpaContractBpaReviewDao;

    @Autowired
    private BudgetBatchInfoDao budgetBatchInfoDao;

    @Autowired
    private BudgetContractDao budgetContractDao;

    @Autowired
    private OAFlowService oaFlowService;

    @Autowired
    private BpaProcessManageService bpaProcessManageService;
	
	@Override
	public GenericDao<BudgetBatch, String> getDao() {
		return null;
	}

    @Override
    public Page<BudgetListDto> selectByDomainWhere(Page<BudgetListDto> page,
                                                       BudgetListVo budgetListVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        Page<BudgetListDto> pageList = new Page<BudgetListDto>();
        pageList = budgetBatchDao.selectListByDomainWhere(budgetListVo);
        return pageList;
    }

    @Override
    public Page<BudgetBatchDomain> selectMyCheckByDomainWhere(Page<BudgetBatchDomain> page, BudgetBatchVo budgetBatchVo) {
        return null;
    }

    @Override
    public BudgetBatchDetailJsonVo getDetail(String id) {
        //判断id是否为空 如果为空则表示是新增 不为空表示是详情页面
        BudgetBatchDetailJsonVo budgetBatchDetailJsonVo = new BudgetBatchDetailJsonVo();
        if(StringUtils.isBlank(id)){
            budgetBatchDetailJsonVo = addDetailReturnData(budgetBatchDetailJsonVo);
        }else {
            budgetBatchDetailJsonVo = detailReturnData(id, budgetBatchDetailJsonVo);
        }
        return budgetBatchDetailJsonVo;
    }

    @Override
    public BudgetBatchDetailJsonVo getProInfoAndContract(String proCode) {
        BudgetBatchDetailJsonVo vo = new BudgetBatchDetailJsonVo();
	    //获取项目信息
        BpaPublicProInfoDto dto = projectInfoService.queryBpaProInfoByProCode(proCode);
        BudgetBatchDetailDto info = new BudgetBatchDetailDto();
        BeanUtils.copyProperties(dto, info);
        vo.setInfo(info);
        //获取合同列表
        List<Map<String,String>> listMap = new ArrayList<>();
        List<BpaContractBpaReview> list = bpaContractBpaReviewDao.selectByProCode(proCode);
        for(BpaContractBpaReview bpaContractBpaReview : list){
            HashMap<String,String> map = new HashMap<>();
            map.put(bpaContractBpaReview.getId(),bpaContractBpaReview.getNegName());
            listMap.add(map);
        }
        return vo;
    }

    @Override
    public BudgetBatchDetailJsonVo queryBudgetInfoByContractId(String contractId) throws Exception {
        BudgetBatchDetailJsonVo vo = new BudgetBatchDetailJsonVo();
        //获取子项下拉列表
        List<BpaContractListing> list = bpaContractBpaReviewDao.querySubByContractId(contractId);
        List<Map<String,String>> listMap = new ArrayList<>();
        for(BpaContractListing bpaContractListing : list){
            HashMap<String,String> map = new HashMap<>();
            map.put("itemType", bpaContractListing.getItemType());
            map.put("itemName", bpaContractListing.getItemName());
            listMap.add(map);
        }
        vo.setSubList(listMap);
        //获取费用清单内容
        List<BudgetContract> budgetContractList = null;//费用清单信息
        List<BpaContractListing> listing = bpaContractBpaReviewDao.selectListing(contractId,"1");
        for(BpaContractListing bpaContractListing:listing){
            BudgetContract budgetContract = new BudgetContract();
            BeanUtils.copyProperties(bpaContractListing, budgetContract);
            budgetContractList.add(budgetContract);
        }
        vo.setBudgetContractList(budgetContractList);
        return vo;
    }

    @Override
    public RspVo save(BudgetBatchDetailJsonVo detailJson, Integer submitType, AuthorizationVO vo) {
        BudgetBatchDetailDto budgetBatchDetailDto = detailJson.getInfo();
        BudgetBatch budgetBatch = detailJson.getBudgetBatch();
        BudgetBatch budgetBatchDto = new BudgetBatch();
        BeanUtils.copyProperties(budgetBatch, budgetBatchDto);
        budgetBatchDto.setUptBy(vo.getId());
        budgetBatchDto.setUptTime(new Date());
        budgetBatchDto.setProCode(budgetBatchDetailDto.getProCode());
        if(StringUtils.isBlank(budgetBatch.getId())){
            //新增
            budgetBatchDto.setAddBy(vo.getId());
            budgetBatchDto.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            budgetBatchDto.setCodes(IdFactory.getUUIDUpper());
            budgetBatchDao.insertSelective(budgetBatchDto);
        }else{
            //校验数据是否存在
            BudgetBatch budgetBatchVO = budgetBatchDao.selectByPrimaryKey(budgetBatch.getId());
            if (budgetBatchVO == null) return RspVo.getFailureResponse(400, "概算分批数据不存在");
            //判断审批状态
            if (StringUtils.isNotBlank(budgetBatchVO.getProcessStatus())
                    && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), budgetBatchVO.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), budgetBatchVO.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            //更新
            budgetBatchDao.updateByPrimaryKeySelective(budgetBatchDto);
            budgetBatchDto.setOaId(budgetBatchVO.getOaId());//预留给OA流程id
        }

        //处理费用清单
        addBudgetContract(detailJson, budgetBatchDto.getId());
        //处理概算清单
        addBudgetInfo(detailJson, budgetBatchDto.getId());

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(detailJson.getFileAtt()!=null){
            String[] fileAtt = detailJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = FileAttrUtils.createProjectFileAtta(budgetBatch.getId(), file);
                attachmentList.add(attachment);
            }
        }
        projectAttachmentDao.deleteByWhere(budgetBatch.getId(), ProjectFileTypeEnum.FILE_TYPE140.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        //提交流程
        if (1 == submitType) {
            //TODO 有可能在同一个事务里面获取不到 budgetBatchVO
            BudgetBatch budgetBatchVO = budgetBatchDao.selectByPrimaryKey(budgetBatch.getId());
            if (StringUtils.isNotBlank(budgetBatchVO.getOaId())) {
                oaFlowService.finishOA(budgetBatchVO.getOaId());
            }
            BudgetBatchDetailJsonVo budgetBatchDetailJsonVo = getDetail(budgetBatchVO.getId());
            String json = JSON.toJSONString(budgetBatchDetailJsonVo);
            bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE27, json, budgetBatchVO.getId(), budgetBatchVO.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    //新增费用列表
    private void addBudgetContract(BudgetBatchDetailJsonVo detailJson,String id){
        budgetContractDao.deleteByContractId(id);
        List<BudgetContract> budgetContractList = detailJson.getBudgetContractList();
        if (budgetContractList != null && budgetContractList.size() > 0) {
            for (BudgetContract budgetContract : budgetContractList) {
                budgetContract.setContractId(id);//主表id
                budgetContractDao.insertSelective(budgetContract);
            }
        }
    }

    //新增概算清单列表
    private void addBudgetInfo(BudgetBatchDetailJsonVo detailJson,String id){
        List<BudgetBatchInfo> budgetBatchInfoList = detailJson.getBudgetBatchInfoList();
        budgetBatchInfoDao.deleteByBudgetId(id);
        if (budgetBatchInfoList != null && budgetBatchInfoList.size() > 0) {
            for (BudgetBatchInfo budgetBatchInfo : budgetBatchInfoList) {
                budgetBatchInfo.setBudgetId(id);//合同id
                budgetBatchInfoDao.insert(budgetBatchInfo);
            }
        }
    }

    //查看详情的数据返回
    public BudgetBatchDetailJsonVo detailReturnData(String id, BudgetBatchDetailJsonVo budgetBatchDetailJsonVo){
        //主表信息
	    BudgetBatch budgetBatch = budgetBatchDao.selectByPrimaryKey(id);
        budgetBatchDetailJsonVo.setBudgetBatch(budgetBatch);
        //获取项目信息
        BpaPublicProInfoDto  dto = projectInfoService.queryBpaProInfoByProCode(budgetBatch.getProCode());
        BudgetBatchDetailDto info = new BudgetBatchDetailDto();
        info.setId(id);
        info.setApplyCompName(dto.getApplyCompName());
        info.setApplyDeptName(dto.getApplyDeptName());
        info.setApplyStaffName(dto.getApplyStaffName());
        info.setAreaCompName(dto.getAreaCompName());
        info.setCoopName(dto.getCoopName());
        info.setProCode(dto.getProCode());
        info.setProCompName(dto.getProCompName());
        info.setProStaffName(dto.getProStaffName());
        info.setSgCityName(dto.getSgCityName());
        info.setProStaffName(dto.getProStaffName());
        budgetBatchDetailJsonVo.setInfo(info);
        //项目列表
        //概算清单
        List<BudgetBatchInfo> BudgetBatchInfoList = budgetBatchInfoDao.selectByGudgetId(id);
        budgetBatchDetailJsonVo.setBudgetBatchInfoList(BudgetBatchInfoList);
        //费用清单
        List<BudgetContract> budgetContractList  = budgetContractDao.selectByGudgetId(id);
        budgetBatchDetailJsonVo.setBudgetContractList(budgetContractList);
        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(id, ProjectFileTypeEnum.FILE_TYPE141.getCode(), null);
        budgetBatchDetailJsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        return budgetBatchDetailJsonVo;
    }

    //新增的数据封装返回
    public BudgetBatchDetailJsonVo addDetailReturnData(BudgetBatchDetailJsonVo budgetBatchDetailJsonVo){
        //返回所有的项目code和name
        budgetBatchDetailJsonVo.setProInfoList(setupProService.queryPublicProInfo());
        return budgetBatchDetailJsonVo;
    }

    @Override
    public BudgetBatchVo queryById(String id) {
        return null;
    }

}